import { Ref, SetupContext, ref, watch } from "vue";
import { InputGroupProps } from "../input-group.props";
import { UseAppendedButton, UsePassword } from "./types";

export function usePassword(
    props: InputGroupProps,
    context: SetupContext,
    inputType: Ref<string>,
    useAppendedButtonComposition: UseAppendedButton
): UsePassword {
    const { appendedContent } = useAppendedButtonComposition;
    const enableViewPassword = ref(props.enableViewPassword);
    const isPassword = ref(props.isPassword);

    const shownPasswordContent = '<span class="f-icon f-icon-eye" style="color: rgb(56, 143, 255);"></span>';
    const hiddenPasswordContent = '<span class="f-icon f-icon-eye"></span>';
    const shouleShowPassword = ref(false);

    watch(() => [props.readonly, props.disabled], ([readonly, disabled]) => {
        if (isPassword.value) {
            inputType.value = (readonly || disabled) ? 'password' : inputType.value;
            appendedContent.value = (readonly || disabled) ? hiddenPasswordContent : appendedContent.value;
        }
    });

    function onClickAppendedButton() {
        shouleShowPassword.value = !shouleShowPassword.value;
        inputType.value = shouleShowPassword.value ? 'text' : 'password';
        appendedContent.value = shouleShowPassword.value ? shownPasswordContent : hiddenPasswordContent;
        return false;
    }

    function resetPaaswordOptions() {
        inputType.value = isPassword.value ? 'password' : 'text';
        appendedContent.value = isPassword.value ? (enableViewPassword.value ? hiddenPasswordContent : '') : appendedContent.value;
    }

    resetPaaswordOptions();

    return { isPassword, onClickAppendedButton };
}
